package com.li.chat.utils;

import io.minio.*;
import io.minio.http.Method;
import io.minio.messages.DeleteObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Component
public class MinioUntil {

    private static final String BUCKETNAME = "bucket-chat";

    @Autowired
    MinioClient minioClient;


    public Map<String, String> upload(MultipartFile file) {

        String filename = file.getOriginalFilename();
        try {
            InputStream inputStream = file.getInputStream();
            // 上传到minio服务器
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(BUCKETNAME)
                    .object(filename)
                    .stream(inputStream, file.getSize(), 10485760L)
                    .build());
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 返回地址
        Map<String,String > resultMap = new HashMap<>();
        resultMap.put("fileName",filename);
        resultMap.put("url",getUrl(filename));
        return  resultMap;
    }

    public Map<String, String> removeObjects(String fileName) {
        Map<String,String > resultMap = new HashMap<>();
        //List<DeleteObject> dos = objects.stream().map(e -> new DeleteObject(e)).collect(Collectors.toList());
        try {
            minioClient.removeObject(RemoveObjectArgs.builder().bucket(BUCKETNAME).object(fileName).build());
            resultMap.put("mes","删除成功");
        }catch (Exception e){
            e.printStackTrace();
            resultMap.put("mes","网络异常，删除失败");
        }
        return resultMap;
    }
    public String getUrl(String objectName){
        String url=new String();
        try {
            url = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
                    .method(Method.GET)
                    .bucket(BUCKETNAME)
                    .object(objectName)
                    .expiry(1, TimeUnit.DAYS)
                    .build());
        }catch (Exception e){
            e.printStackTrace();
        }
        return url;
    }
}
